package com.wsj.util.tool;


import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Random;
import java.util.StringTokenizer;


/**
 * ���ߣ��� һЩ�����ַ�Ĺ��ߺ���
 */
public class StringUtil {

	
	/**
	 * ȡ���Զ���λ�������
	 * @param size λ��
	 * @return
	 */
	public static String RandomStr(int size) {
		Random random = new Random();
		String sRand = "";
		for (int i = 0; i < size; i++) {
			String rand = String.valueOf(random.nextInt(10));
			sRand += rand;
		}
		
		return sRand;
	}

	
	/**
     * ���ı���ת��
     *
     * @param str String
     * @return String
     */
    public static String toGBK(String str)
    {
        if(str != null)
        {
            try
            {
                str = new String(str.trim().getBytes("ISO8859-1"));//������
            }
            catch(Exception e)
            {
                e.printStackTrace();
            }
        }
        return str;
    }
	
    /**
     * �ж��Ƿ�������
     * @param num
     * @return
     */
    public static boolean isNum(String num) {
		try {
			Long.parseLong(num);
		}
		catch (NumberFormatException e) {
			return false;
		}
		return true;
	}
    
    
    /**
     * ���ַ�����ַ�ָ����List
     * @param strData
     * @param strDelim
     * @return
     */
	public static ArrayList getTokenArray(String strData, String strDelim) {
		StringTokenizer tokenizer = new StringTokenizer(strData, strDelim);
		ArrayList<String> arrayList = new ArrayList<String>();
		while (tokenizer.hasMoreTokens()) {
			arrayList.add(tokenizer.nextToken());
		}
		return arrayList;
	}
	public static int getCount(String str,String sign){//����ĳһ�ַ���str���ض��Ӵ�s�ĳ��ִ���
	      if(str==null) return 0;
	      StringTokenizer s=new StringTokenizer(str,sign);
	      return s.countTokens();
	 }
	public static String Nulltospase(String str) {
		if(str==null) {
			return "";
		}else {
			return str;
		}		
	}
	
	public static String Nulltospase(String str,String def) {
		if(str==null) {
			return def;
		}else {
			return str;
		}		
	}
	
	public static String deleteCharacter(String string, char delchar) {
		StringBuffer stringBuffer = new StringBuffer(string);
		for (int i = stringBuffer.length() - 1; i >= 0; i--) {
			if (stringBuffer.charAt(i) == delchar) {
				stringBuffer.deleteCharAt(i);
			}
		}
		return stringBuffer.toString();
	}

	public static String sanitize(String input) {
		input = replaceString(input, "&", "&amp;"); // & �� &amp;
		input = replaceString(input, "<", "&lt;"); // < �� &lt;
		input = replaceString(input, ">", "&gt;"); // > �� &gt;
		input = replaceString(input, "\"", "&quot;"); // " �� &quot;
		input = replaceString(input, "'", "&#39;"); // ' �� &#39;
		return input;
	}

	public static String Htmlclear(String input) {
		input = replaceString(input, "&", "&amp;"); // & �� &amp;
		input = replaceString(input, "<", "&lt;"); // < �� &lt;
		input = replaceString(input, ">", "&gt;"); // > �� &gt;
		input = replaceString(input, "\"", "&quot;"); // " �� &quot;
		input = replaceString(input, "'", "&#39;"); // ' �� &#39;
		return input;
	}

/**
 * ��4�滻��start��ʼ��end������ַ�
 * @param input
 * @param start
 * @param end
 * @param str 
 * @return
 */
	public static String replaceString(String input, String start, String end,	String str) {
		String output = input.toLowerCase();
		start=start.toLowerCase();
		end=end.toLowerCase();
		if (str.indexOf(start) != -1 && str.indexOf(end) != -1)
			return input;// ��ֹ������ѭ��
		int i=0;
		while (output.indexOf(start) != -1 && output.indexOf(end) != -1&&i<100) {
			int spoint = output.indexOf(start);
			int epoint = output.indexOf(end) + end.length();
			if (spoint < epoint) {
				input=input.substring(0,spoint)+str+input.substring(epoint,input.length());
				output=output.substring(0,spoint)+str+output.substring(epoint,output.length());
			} else {
				output = output.replaceFirst(end, "##########");
				input = input.replaceFirst(input.substring(epoint
						- end.length(), epoint), "##########");
			}
		}

		return input.replaceAll("##########", end);
	}

/**
 * �����Ե�һ���� start��ʼ�� end �����ַ� 
 * @param input
 * @param start
 * @param end
 * @param key 0-����html��ǩ  ��1 -��ȥhtml��ǩ
 * @return
 */
	public static String getFirststr(String input,String start,String end,int key){
		String output = input.toLowerCase();
		start=start.toLowerCase();
		end=end.toLowerCase();
		String temp="";	
			int spoint = -1;
			if(!input.equals("")){
				if(start.indexOf("^^^")==-1){
					spoint=output.indexOf(start)+start.length();
					if(spoint!=-1)temp=output.substring(spoint,output.length());
				}else{
					String[] l=start.split("\\^\\^\\^");
					int tempsport=0;
					temp=output;
					for(int i=0;i<l.length;i++){
						spoint=temp.indexOf(l[i])+l[i].length();
						if(spoint==-1) break;
						temp=temp.substring(spoint,temp.length());
						tempsport+=spoint;
					}
					spoint=tempsport;
				}
			}
			int epoint=-1;
			if(!end.equals("")){
				epoint=temp.indexOf(end);// + end.length();
			}
		if(spoint!=-1&&epoint!=-1){
			output=output.substring(spoint,spoint+epoint);
		}else{
			output="";
		}
		if(key==1)output=replaceString(output,"<",">","");
		return output;
	}
	
	
	/**
	 * 
	 * @param input
	 * @param start��ʼ
	 * @param end ����
	 * @param str
	 * @return
	 */
	private static String cleartags(String input, String start, String end,	String str) {
		String output = input.toLowerCase();
		start=start.toLowerCase();
		end=end.toLowerCase();
		if (str.indexOf(start) != -1 && str.indexOf(end) != -1)
			return input;// ��ֹ������ѭ��
		int i=0;
		while (output.indexOf(start) != -1 && output.indexOf(end) != -1&&i<100) {
			int spoint = output.indexOf(start)+1;
			int epoint = output.indexOf(end) + end.length();
			if (spoint < epoint) {
				input=input.substring(0,spoint)+str+input.substring(epoint,input.length());
				output=output.substring(0,spoint)+str+output.substring(epoint,output.length());
			} else {
				output = output.replaceFirst(end, "##########");
				input = input.replaceFirst(input.substring(epoint
						- end.length(), epoint), "##########");
			}
		}

		return input.replaceAll("##########", end);
	}
	/**
	 * ��ȡ���ı���Ϣ
	 * @param input
	 * @return
	 */
	public static String noHtmltags(String input) {
		input = cleartags(input, "<script", "</script", "");
		input = cleartags(input, "<style", "</style", "");
		input = cleartags(input, "<!--", "-->", "");
		input = cleartags(input, "<embed", "</embed>", "");
		input = cleartags(input, "<NOEMBED>", "</NOEMBED>", "");
		input = cleartags(input, "<NOSCRIPT>", "</NOSCRIPT>", "");				
		input = input.replaceAll("<>", "");
		input = StringUtil.noHtmltags(input);
		input = input.replaceAll("&nbsp;", "");
		
		return input;
	}

	/**
	 * �ַ��滻
	 * @param input
	 * @param befor
	 * @param after
	 * @return
	 */
	public static String replaceString(String input, String befor, String after) {
		StringBuffer output = new StringBuffer(input);
		int index = input.indexOf(befor);
		while (index != -1) {
			output.replace(index, index + befor.length(), after);
			index = output.toString().indexOf(befor, index + 1);
		}
		return output.toString();
	}

	


	public static String enclose(String val) {
		return "\"" + val + "\"";
	}




	/**
	 * ���ܣ�����ת�� ���� String ���أ� String
	 */
	public static String formatDate(String date) {
		if (date == null || date.equals(""))
			return "";
		date=codatestr(date);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		return sdf.format(Timestamp.valueOf(date));
	}

	/**
	 * ���ڸ�ʽ��
	 * 
	 * @param date
	 * @param style��yyyy/MM/dd
	 *            HH:mm:ss
	 * @return
	 */
	public static String formatDate(String date, String style) {
		if (date == null || date.equals(""))
			return "";
		if (style.equals(""))style = "yyyy-MM-dd";
		date=codatestr(date);
		SimpleDateFormat sdf = new SimpleDateFormat(style);
		return sdf.format(Timestamp.valueOf(date));
	}

	/**
	 * ���ܣ��õ�ϵͳ���� ���أ� String
	 */
	public static String getSysDate() {
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		return sdf.format(date);
	}

	/**
	 * ���ܣ� �õ���ǰҳ�� ���� �� ���أ� int
	 */
	public static int getCurrentPage(int recordCount, int maxLine,
			int currentPage) {
		int pageMax;

		if (currentPage < 1) {
			currentPage = 1;
		} else {
			pageMax = getMaxPage(recordCount, maxLine);
			if (currentPage > pageMax) {
				currentPage = pageMax;
			}
		}

		return currentPage;
	}

	/**
	 * ���ܣ��õ����ҳ�� ���� �� ���أ� int
	 */
	public static int getMaxPage(int recordCount, int maxLine) {
		int pageCount;

		pageCount = recordCount / maxLine;
		if (pageCount * maxLine != recordCount) {
			pageCount = pageCount + 1;
		}

		return pageCount;
	}

	/**
	 * ���ܣ����ڴ��� ���� �� ���أ� String
	 */
	public static String processDate(Object date) {
		if (date == null)
			return "";
		String locDate = date.toString();

		return formatDate(locDate);

	}

	/**
	 * ���ܣ����ڴ��� ���� �� ���أ� String
	 */
	public static String processTime(Object time) {
		if (time == null)
			return "";
		String locDate = time.toString();

		return formatTime(locDate);

	}
	
	/**
	 * 
	 * @param date yyyy-MM-dd HH:mm:sss
	 * @return /yyyy/MM/dd
	 */
	public static String getfpath(String date) {
		if(!date.equals("")) {
			date=codatestr(date);
		return formatDate(date,"yyMMdd");
		}else {
			return "";
		}
	}
	
	private static String codatestr(String datein) 
	{
		if(datein.length()<=10) {
			datein=datein+" 00:00:000";
		}
		return datein;
	}
	
	
	/**
	 * ���ܣ�����ת�� ���� String ���أ� String
	 */
	public static String formatTime(String time) {
		if (time == null || time.equals(""))
			return "";
		time=codatestr(time);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return sdf.format(Timestamp.valueOf(time));

	}

	/**
	 * ���ܣ��õ���ǰʱ�� ���أ� String
	 */
	public static String getCurformatTime() {
		String datestr="";
		Date time = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		datestr=sdf.format(time);
		return datestr;

	}

	/**
	 * ���ܣ����ֱ༭,����".2"��ʽ���ַ�����"0.2" ���� String ���أ� String
	 */
	public static String number_editing(String numerical_value) {

		if (numerical_value.equals(""))
			return "";

		DecimalFormat df = new DecimalFormat("0.####");

		Double num = new Double(numerical_value);

		return (df.format(num.doubleValue())).toString();
	}

	

	/**
	 * ���ܣ�ת�������� ���� String ���أ� String
	 */
	public static String transChina(String str) {
		try {
			String retStr = new String(str.getBytes("ISO8859_1"), "gb2312");
			return retStr;
		} catch (Exception e) {
		}
		return "error";
	}

	/**
	 * ���ܣ�ת����Float ���� String ���أ� Float
	 */
	public static float transFloat(String str) {
		float ret = 0;
		if (str != null && !str.equals("")) {
			ret = Float.parseFloat(str);
		}

		return ret;
	}

	/**
	 * ���ܣ��������ַ�ת����HTML��ʽ���ַ� ���� String ���أ� String
	 */
	public static String transToHtmlChar(String str) {
		str = replaceString(str, " ", "&nbsp;");
		str = replaceString(str, "\n", "<br>");
		str = replaceString(str, "\t", "&nbsp;&nbsp;&nbsp;&nbsp;");
		return str;
	}

	
/**
 * ��ȡ�ַ� ȡǰlen/2���֣�һ����ռ}���ֽ�
 * @param str
 * @param len
 * @return
 */
	public static String maxLenString(String str, int len) {
		return maxLenString(str,len,"...");
	}
	/**
	 * ��ȡ�ַ� ȡǰlen/2���֣�һ����ռ}���ֽ�
	 * @param str
	 * @param len
	 * @param zhui  ...
	 * @return
	 */
	public static String maxLenString(String str,int len,String zhui){
		if(str!=null) {
			str=noHtmltags(str);
			StringBuffer output = new StringBuffer();
			String mstr="";
			int t=0;
			int l=str.length();
			for(int i=0;i<l;i++) {
				mstr=str.substring(i,i+1);
				t+=mstr.getBytes().length;
				if(t<=len) {
					output.append(mstr);
				}else {
					i=l;
					output.append(zhui);
				}
			}
			return output.toString();
		}else {
			return "";
		}
	}
	
	
	
	/**
	 * �����ݿ�(SQL-SERVER 2K)���������ȡ��JAVA�������
	 * 
	 * @param dataType
	 * @return
	 */
	public static String getDataType(String dataType) {

		String retValue = "";

		if (dataType.equals("bit") || dataType.equals("varchar")
				|| dataType.equals("char") || dataType.equals("nchar")
				|| dataType.equals("ntext") || dataType.equals("nvarchar")
				|| dataType.equals("text")) {
			retValue = "String";
		}

		if (dataType.equals("bigint") || dataType.equals("int")
				|| dataType.equals("smallint") || dataType.equals("tinyint")) {
			retValue = "int";
		}

		if (dataType.equals("datetime") || dataType.equals("smalldatetime")
				|| dataType.equals("timestamp")) {
			retValue = "Date";
		}

		if (dataType.equals("float") || dataType.equals("money")
				|| dataType.equals("numeric") || dataType.equals("real")
				|| dataType.equals("smallmoney")) {
			retValue = "double";
		}

		return retValue;
	}

	/**
	 * url ����
	 * 
	 * @param src
	 *            ��Ӧjavascript �е�escape()
	 * @return
	 */
	public static String escape(String src) {
		int i;
		char j;
		StringBuffer tmp = new StringBuffer();
		tmp.ensureCapacity(src.length() * 6);
		for (i = 0; i < src.length(); i++) {
			j = src.charAt(i);
			if (Character.isDigit(j) || Character.isLowerCase(j)
					|| Character.isUpperCase(j))
				tmp.append(j);
			else if (j < 256) {
				tmp.append("%");
				if (j < 16)
					tmp.append("0");
				tmp.append(Integer.toString(j, 16));
			} else {
				tmp.append("%u");
				tmp.append(Integer.toString(j, 16));
			}
		}
		return tmp.toString();
	}

	/**
	 * url ����
	 * 
	 * @param src
	 *            ��Ӧjavascript �е�unescape()
	 * @return
	 */
	public static String unescape(String src) {
		StringBuffer tmp = new StringBuffer();
		tmp.ensureCapacity(src.length());
		int lastPos = 0, pos = 0;
		char ch;
		while (lastPos < src.length()) {
			pos = src.indexOf("%", lastPos);
			if (pos == lastPos) {
				if (src.charAt(pos + 1) == 'u') {
					ch = (char) Integer.parseInt(src
							.substring(pos + 2, pos + 6), 16);
					tmp.append(ch);
					lastPos = pos + 6;
				} else {
					ch = (char) Integer.parseInt(src
							.substring(pos + 1, pos + 3), 16);
					tmp.append(ch);
					lastPos = pos + 3;
				}
			} else {
				if (pos == -1) {
					tmp.append(src.substring(lastPos));
					lastPos = src.length();
				} else {
					tmp.append(src.substring(lastPos, pos));
					lastPos = pos;
				}
			}
		}
		return tmp.toString();
	}
	
	/**
	 * ��ʱ����ת���� Сʱ �� ��
	 * @param timeInSeconds
	 * @return 
	 */
	public static String formatTime(double timeInSeconds) {
		long seconds = (long) Math.floor(timeInSeconds);
		long minutes = (long) Math.floor(timeInSeconds / 60.0);
		long hours = (long) Math.floor(minutes / 60.0);

		if (hours != 0) {
			return hours + "ʱ" + (minutes % 60) + "�� "
					+ (seconds % 60) + "��";
		} else if (minutes % 60 != 0) {
			return (minutes % 60) + "��" + (seconds % 60) + "��";
		} else {
			return (seconds % 60) + "��";
		}
	}
	
	
	/**
	 * ��û�д������յ��û�����һ��Ĭ��ͼƬ
	 * @param img
	 * @param userid
	 * @return
	 */
	public static String defimg(int userid) {
		String path="http://img.13nr.com/defimg/com/img";
		int n=0-(userid%33);
		if(userid>0) {
			path="http://img.13nr.com/defimg/user/img";
			n=userid%107;
		}
		path+=n+".jpg";	
		return path;
	}
	
	/**
	 * �ж���-�˵��ǲ��Ǳ�ѡ��
	 * @param str ��ʵ�������
	 * @param pstr ���ؼ������
	 * @return
	 */
   public static String isSelected(String str,String pstr){
	   String sta = "selected";
	   if(str!=null && str.equals(pstr))return sta;
	   else return "";
   }
   
   /**
	 * �жϵ�ѡ��Ŧ�ǲ���ѡ��
	 * @param str ��ʵ�������
	 * @param pstr ���ؼ������
	 * @return
	 */
  public static String isChecked(String str,String pstr){
	   String sta = "checked";
	   if(str!=null && str.equals(pstr))return sta;
	   else return "";
  }
  /**
   * �ж϶�ѡ�ǲ���ѡ��
   * @param str
   * @param pstr
   * @return
   */
  public static String isCheckedMutiple(String str,String pstr){
	  String sta = "checked";
	  if(str.indexOf(pstr)!=-1)return sta;
	  else return "";
	  
  }
	
  /**
   * �ж��ַ��Ƿ�Ϊʱ���ʽ
   * @param timestr
   * @param str
   * @return
   */
  public static boolean isDate(String timestr,String str){
	   	if(str.equals(""))str="yyyy-MM-dd";
        SimpleDateFormat   sdf   =   new   SimpleDateFormat(str);   
        try   {   
          if   (sdf.format(sdf.parse(timestr)).equalsIgnoreCase(timestr))     
        	  return true;
          else     
        	  return false;  
        }   catch   (Exception   ex)   {   
              return false;   
        }

  }
	
  /**
   * 把字符形数组，转换成型数组。
   * @param strArray
   * @return int[]
   */
  public static int[] changeStrArrayToIntArray(String[] strArray){
	  int[] intArray = null;
	  if(strArray==null||strArray.length==0){
		  return null;
	  }else{
		  int i = strArray.length;
		  intArray = new int[i];
		  try{
				  for(int j=0;j<i;j++){
					  intArray[j] = Integer.parseInt(strArray[j]);
				  }
		  }catch(Exception fmtex){
			  return null;
		  }
	  }
	  return intArray;
  }
  public static long[] changeStrArrayToLongArray(String[] strArray){
	  long[] intArray = null;
	  if(strArray==null||strArray.length==0){
		  return null;
	  }else{
		  int i = strArray.length;
		  intArray = new long[i];
		  try{
				  for(int j=0;j<i;j++){
					  intArray[j] = Long.parseLong(strArray[j]);
				  }
		  }catch(Exception fmtex){
			  return null;
		  }
	  }
	  return intArray;
  }
  
  /**
   * 把字符形数组，转换成型数组。
   * @param strArray
   * @return int[]
   */
  public static int[] changeStrToStringArrToIntArray(String str){
	  int[] intArray = null;
	  if(str==null){
		  return null;
	  }else{
		  String []strArray;
		  strArray = str.split(",");
		  int i = strArray.length;
		  intArray = new int[i];
		  try{
				  for(int j=0;j<i;j++){
					  intArray[j] = Integer.parseInt(strArray[j]);
				  }
		  }catch(Exception fmtex){
			  return null;
		  }
	  }
	  return intArray;
  }
  
  
  /********
   * 去掉字符串中的所有html标记
   */
  public static String clearHtmlMark(String str)
  {
	  String ret="";
	  //ret = Regex.Replace(str,"<[\\/\\!]*?[^<>]*?>","");
	  if(str!=null)
	  {
		 ret =str.replaceAll("<[\\/\\!]*?[^<>]*?>", "");
         ret = ret.replaceAll("&nbsp;", ""); 
	  }
      return ret;
  }
  
	
}




